<template>
  <div class="preview">
    <el-form
      :rules="rules"
      :ref="formConf.formModel"
      :size="formConf.size"
      :model="form"
      :label-position="formConf.labelPosition"
      :disabled="formConf.disabled"
      :validate-on-rule-change="false"
      :label-width="formConf.labelWidth + 'px'"
    >
      <template v-for="(element, index) in list" :key="element.id">
        <!-- 行组件处理（支持嵌套） -->
        <preview-row-item 
          v-if="element.compType === 'row'" 
          :model="element"
          @valChange="handlerValChange"
        >
          <el-col 
            v-for="column in element.columns" 
            :key="column.index" 
            v-bind="getColProps(column)"
          >
            <template v-for="col in column.list">
              <preview-item
                v-if="col.compType !== 'dynamicTable'"
                :key="col.id"
                :model="col"
                v-model="form[col.id]"
                @valChange="handlerValChange"
              />
              <fancy-dynamic-table
                v-else
                :key="'dynamic-' + col.id"
                :data="form[col.id]"
                :conf="col"
                @addRow="handlerAddRow"
                @deleteRow="handlerDeleteRow"
              >
                <template #item="{ rowScope, item }">
                  <fancy-dynamic-table-item
                    :model="item"
                    :parent="col"
                    v-model="rowScope.row[item.id]"
                    @valChange="(val) => handleDynamicValChange(col.id, rowScope.$index, item.id, val)"
                  />
                </template>
              </fancy-dynamic-table>
            </template>
          </el-col>
        </preview-row-item>

        <!-- 动态表格处理 -->
        <fancy-dynamic-table
          v-else-if="element.compType === 'dynamicTable'"
          :data="form[element.id]"
          :conf="element"
          @addRow="handlerAddRow"
          @deleteRow="handlerDeleteRow"
        >
          <template #item="{ rowScope, item }">
            <fancy-dynamic-table-item
              :model="item"
              v-model="rowScope.row[item.id]"
              @valChange="(val) => handleDynamicValChange(element.id, rowScope.$index, item.id, val)"
            />
          </template>
        </fancy-dynamic-table>

        <!-- 静态表格处理 -->
        <fancy-edit-table
          v-else-if="element.compType === 'table'"
          :layoutArray="element.layoutArray"
          :tdStyle="element.tdStyle"
        >
          <template #default="{ td }">
            <template v-for="col in td.columns" :key="col.id">
              <preview-item
                :model="col"
                v-model="form[col.id]"
                @valChange="handlerValChange"
                @clear="handlerValChange"
              />
            </template>
          </template>
        </fancy-edit-table>

        <!-- 默认组件处理 -->
        <el-col 
          v-else
          class="drag-col-wrapper" 
          :span="element.span"
        >
          <preview-item
            :model="element"
            v-model="form[element.id]"
            @valChange="handlerValChange"
          />
        </el-col>
      </template>
    </el-form>
    <el-divider></el-divider>
    <div style="text-align: center">
      <el-button type="primary" @click="handlerSubForm">提交</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, VueHook } from 'web-decorator-vue';
import previewItem from './previewItem';
import previewRowItem from './preview-row-item.vue';
import fancyDynamicTable from '../formDesigner/dynamic/fancyDynamicTable.vue';
import fancyDynamicTableItem from './dynamic/fancyDynamicTableItem';
import fancyEditTable from './table/fancyEditTable.vue';
import { datas, addRow, batchDeleteRow, deleteRow } from './custom/formDraw';

interface FormConfig {
  formModel: string;
  size: string;
  labelPosition: string;
  labelWidth: number;
  disabled: boolean;
  [key: string]: any;
}

interface FormElement {
  id: string;
  compType: string;
  modelValue?: any;
  columns?: Array<{
    list: FormElement[];
    [key: string]: any;
  }>;
  [key: string]: any;
}

@Component({
  name: 'preview',
  components: {
    previewItem,
    previewRowItem,
    fancyDynamicTable,
    fancyDynamicTableItem,
    fancyEditTable
  }
})
export default class Preview {
  @Prop() itemList!: FormElement[];
  @Prop() formConf!: FormConfig;

  list: FormElement[] = [];
  form: Record<string, any> = {};
  rules: Record<string, any> = {};
  currentIndex: number = -1;
  $refs: any
  @VueHook()
  created() {
    this.handlerInitDatas();
    this.list = this.itemList;
    this.initFormModel();
  }

  /**
   * 初始化表单数据模型（支持嵌套结构）
   */
  private initFormModel() {
    const buildModel = (elements: FormElement[], parentPath = ''): Record<string, any> => {
    return elements.reduce((model, element) => {
      const currentPath = parentPath ? `${parentPath}.${element.id}` : element.id;
      
      if (element.compType === 'row') {
        // 行组件不需要在form中创建字段，只需要处理其子组件
        element.columns?.forEach(column => {
          Object.assign(model, buildModel(column.list, currentPath));
        });
      } else if (element.compType === 'dynamicTable') {
        model[element.id] = [{}]; // 动态表格特殊处理
      } else {
        model[element.id] = element.modelValue ?? '';
      }
      return model;
    }, {});
  };

  this.form = buildModel(this.itemList);
  }

  /**
   * 获取组件类型
   */
  getComponentType(element: FormElement) {
    return element.compType === 'dynamicTable' ? fancyDynamicTable : previewItem;
  }

  /**
   * 获取字段路径（处理嵌套）
   */
  getFieldPath(parent: FormElement, child: FormElement) {
    return child.id;
  }

  /**
   * 处理嵌套值变化
   */
  handlerValChange(key: string, origin: any) {
    console.log(key);
    console.log(origin);
    //@ts-ignore
    this.form[key] = origin;
  }

  /**
   * 处理动态表格值变化
   */
  handleDynamicValChange(tableId: string, rowIndex: number, field: string, value: any) {
    if (!this.form[tableId]) {
      this.$set(this.form, tableId, []);
    }
    if (!this.form[tableId][rowIndex]) {
      this.$set(this.form[tableId], rowIndex, {});
    }
    this.$set(this.form[tableId][rowIndex], field, value);
    this.currentIndex = rowIndex;
  }

  /**
   * 获取列布局属性
   */
  getColProps(column: any) {
    return column.responsive !== false ? {
      xs: column.xs || 24,
      sm: column.sm || column.span || 12,
      md: column.md || column.span || 8,
      lg: column.lg || column.span || 6,
      xl: column.xl || column.span || 4
    } : {
      span: column.span || 12
    };
  }

  /**
   * 表单提交
   */
  handlerSubForm() {
    (this.$refs[this.formConf.formModel] as any)?.validate((valid: boolean) => {
      if (valid) {
        this.$message.success('提交成功');
        console.log('表单数据:', JSON.stringify(this.form, null, 2));
      } else {
        this.$message.error('表单验证失败');
      }
    });
  }

  // 以下方法保持原有实现
  handlerAddRow: any = addRow;
  handlerDeleteRow: any = deleteRow;
  handlerBatchDeleteRow: any = batchDeleteRow;
  handlerInitDatas: any = datas;
}
</script>

<style scoped>
.preview {
  padding: 20px;
}

.drag-col-wrapper {
  padding: 0 7.5px;
  margin-bottom: 15px;
}

.responsive-col {
  margin-bottom: 15px;
}

.nested-row-container {
  /* border: 1px dashed #eee; */
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 15px;
}
</style>